package com.example.jwt.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    @Value("${jwt-secret}")
    private String secret;
    @Value("${jwt-expiration-milliseconds}")
    private long expiration;

    public String generateToken(String username) {
        Map<String, String> claims = new HashMap<>();
        //设置负载
        claims.put("username", username);
        //创建token
        String token = Jwts.builder()
                //设置头部类型和算法
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //加入负载
                .setClaims(claims)
                //设置签发时间
                .setIssuedAt(new Date())
                //设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                //签名
                .signWith(getKey())
                //拼接生成token
                .compact();
        return token;
    }

    private Key getKey() {
        //对密钥进行解码
        return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    }

    //解析token并验证token
    public boolean validateToken(String token) {
        try {
            //创建JWT解析器构建器
            Jwts.parserBuilder()
                    //设置密钥
                    .setSigningKey(getKey())
                    .build()
                    //解析并验证JWT令牌
                    .parseClaimsJws(token);
            return true;
        } catch (MalformedJwtException e) {
            logger.error("Invalid JWT token: {}", e.getMessage());
        } catch (ExpiredJwtException e) {
            logger.error("JWT token is expired: {}", e.getMessage());
        } catch (UnsupportedJwtException e) {
            logger.error("JWT token is unsupported: {}", e.getMessage());
        } catch (IllegalArgumentException e) {
            logger.error("JWT claims string is empty: {}", e.getMessage());
        }
        return false;

    }

    //获得负载
    public Claims getClaims(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
